from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
import uuid

router = APIRouter()


# 数据模型
class Message(BaseModel):
    id: int
    role: str
    content: str
    created_at: datetime


class Conversation(BaseModel):
    id: int
    title: str
    created_at: datetime
    type: str


class CreateConversationRequest(BaseModel):
    title: str
    type: str
    initial_message: Optional[str] = None


class CreateConversationResponse(BaseModel):
    success: bool
    data: Conversation
    message: str
    timestamp: datetime


# Mock数据
conversations_data = [
    {
        "id": 1,
        "title": "深圳监测站分析方法",
        "created_at": datetime.now(),
        "type": "knowledge"
    },
    {
        "id": 2,
        "title": "深圳AQI趋势分析",
        "created_at": datetime.now(),
        "type": "data"
    },
    {
        "id": 3,
        "title": "臭氧变化趋势图分析",
        "created_at": datetime.now(),
        "type": "image"
    },
    {
        "id": 4,
        "title": "Python代码性能分析",
        "created_at": datetime.now(),
        "type": "code"
    }
]


@router.get("/", response_model=List[Conversation])
async def get_conversations():
    """获取所有对话"""
    try:
        return [
            Conversation(**conv) for conv in conversations_data
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{conversation_id}", response_model=List[Message])
async def get_conversation_detail(conversation_id: int):
    """获取对话详情"""
    try:
        # Mock数据 - 根据不同对话类型返回不同的消息
        messages = []
        
        if conversation_id == 2:  # 深圳AQI趋势分析
            messages = [
                {
                    "id": 1,
                    "role": "user",
                    "content": "最近一个月深圳市的AQI变化趋势，请帮我分析一下",
                    "created_at": datetime.now()
                },
                {
                    "id": 2,
                    "role": "assistant",
                    "content": "收到您的请求，我正在分析深圳市最近一个月的AQI数据...",
                    "created_at": datetime.now()
                }
            ]
        
        return [Message(**msg) for msg in messages]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/", response_model=CreateConversationResponse)
async def create_conversation(request: CreateConversationRequest):
    """创建新对话"""
    try:
        new_conversation = Conversation(
            id=len(conversations_data) + 1,
            title=request.title,
            created_at=datetime.now(),
            type=request.type
        )
        
        conversations_data.append(new_conversation.dict())
        
        return CreateConversationResponse(
            success=True,
            data=new_conversation,
            message="对话创建成功",
            timestamp=datetime.now()
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/{conversation_id}")
async def delete_conversation(conversation_id: int):
    """删除对话"""
    try:
        global conversations_data
        conversations_data = [conv for conv in conversations_data if conv["id"] != conversation_id]
        
        return {"success": True, "message": "对话删除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))